package br.quest.gps;

import java.util.List;
import android.location.Location;
import br.quest.models.Waypoint;

public class GpsUtils {

    /**
     * Calculates the distance between two coordinates, using the Haversine formula.
     * 
     * @param pointA The Coordinate for point A
     * @param pointB The Coordinate for point B
     * @return The distance between the two points, in meters
     */
    public static double distance(Location pointA, Location pointB) {
        float[] results = new float[3];
        Location.distanceBetween(pointA.getLatitude(), pointA.getLongitude(), pointB.getLatitude(),
                pointB.getLongitude(), results);
        return results[0];
    }

    /**
     * Calculates the average speed between a set of coordinates
     * 
     * @param points A List containing Waypoints used to calculate the speed
     * @return The average speed, in meters/second, or -1, if not enought points were provided (minimum is two).
     */
    public static double speed(List<Waypoint> points) {
        if (points.size() >= 2) {
            double distance = 0.0;
            long time = 0;
            long previousTime = points.get(0).getTime();
            Location previousCoord = points.get(0).getCoord();
            for (Waypoint point : points) {
                time += (point.getTime() - previousTime);
                previousTime = point.getTime();
                distance += distance(point.getCoord(), previousCoord);
                previousCoord = point.getCoord();
            }
            return (distance / (time / 1000.0));
        }
        return -1;
    }
}
